import LocalStorageManager from "../common/LocalStorageManger";
import UI from "../common/UI";
import { LevelManager, levelManager } from "./LevelManager";
import Piece from "./Piece";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MainScene extends cc.Component {

    @property(cc.Prefab)
    private piecePrefab: cc.Prefab = null

    public margin: number = 4

    public _curLevel: number = 1

    public curPlayLevel: number = 1

    private pieces: Piece[][] = []

    protected async onLoad() {
        await levelManager.init()

        this.curPlayLevel = LocalStorageManager.get('cur_level', 1)
        this.curLevel = this.curPlayLevel

        UI.OnClick(this.node, 'level/left', function () {
            this.curLevel = this._curLevel - 1
        }, this)

        UI.OnClick(this.node, 'level/right', function () {
            this.curLevel = this._curLevel + 1
        }, this)

        UI.OnClick(this.node, 'start', function () {
            cc.director.loadScene('idiom_game')
        }, this)
    }

    private initLevel() {
        let levelInfo = levelManager.level(this._curLevel)
        let gameContentNode = UI.Child(this.node, 'level/content')
        let gameContentHeight: number = gameContentNode.height
        for (let row = 0; row < levelInfo.length; row++) {
            for (let col = 0; col < levelInfo.length; col++) {
                let piece: Piece = null
                this.pieces[row] = this.pieces[row] ? this.pieces[row] : []
                if (this.pieces[row][col]) {
                    piece = this.pieces[row][col]
                } else {
                    let pieceNode = cc.instantiate(this.piecePrefab)
                    pieceNode.setParent(gameContentNode)
                    piece = pieceNode.getComponent(Piece)
                    this.pieces[row][col] = piece
                }

                piece.init(row, col, this._curLevel == this.curPlayLevel ? '?' : levelInfo[row]['text'].charAt(col))
                piece.node.position = cc.v3(this.margin * (col + 1) + piece.node.width * col,
                    gameContentHeight - (this.margin * (row + 1) + piece.node.height * row), 0)
            }
        }
    }

    set curLevel(value) {
        this._curLevel = value
        LevelManager.curLevel = this._curLevel
        UI.Label(this.node, 'level/level', `第${this._curLevel}关`)
        UI.Active(this.node, 'level/left', this._curLevel != 1)
        UI.Active(this.node, 'level/right', this._curLevel != this.curPlayLevel)
        this.initLevel()
    }
}
